package com.publish.file.service.jwt;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.gson.Gson;
import com.publish.file.common.DateUtils;
import com.publish.file.properties.JwtProperties;
import com.publish.file.service.jwt.exception.JwtException;
import com.publish.file.service.jwt.exception.JwtParseErrorException;

@Service
public class JwtServiceImpl implements JwtService {
	@Autowired
	JwtProperties jwtProperties;
	private static final String KEY_USER = "i";
	private Cipher encryptCipher = null; // 加密器
	private Cipher decryptCipher = null; // 解密器
	private Gson gson = new Gson();

	@Override
	public String generateToken(String userName) throws Exception {
		Algorithm algorithm = getAlgorithm();
		Long expiredDuration = jwtProperties.getExpired();
		Date now = new Date();
		Date expiresDate = DateUtils.after(expiredDuration * 1000);

		Map<String, Object> header = new HashMap<String, Object>();
		Payload payload = new Payload();
		payload.setUserName(userName);
		payload.setExpiredDate(expiredDuration);
		payload.setPassword(userName);
		String payloadString = encrypt(gson.toJson(payload));
		String token = JWT.create().withClaim(KEY_USER, payloadString)// 负载 存放信息
				.withIssuedAt(now) // 签发时间
				.withHeader(header) // 头部信息
				.withExpiresAt(expiresDate) // 过期时间
				.sign(algorithm);
		return token;
	}

	@Override
	public Payload vertifyToken(String token) throws JwtException {
		try {
			JwtMapping mapping = new JwtMapping();
			Algorithm algorithm = getAlgorithm();
			JWTVerifier verifier = JWT.require(algorithm).build();
			DecodedJWT jwt = verifier.verify(token);
			String payloadEncryptString = jwt.getClaim(KEY_USER).asString();
			String payloadString = decrypt(payloadEncryptString);
			Payload payload = gson.fromJson(payloadString, Payload.class);
			mapping.setPayload(payload);
			mapping.setCreateDate(jwt.getIssuedAt());
			mapping.setExpiredDate(jwt.getExpiresAt());
			return mapping.getPayload();
		} catch (JWTVerificationException e) {
			e.printStackTrace();
			throw new JwtParseErrorException();
		} catch (Exception e) {
			e.printStackTrace();
			throw new JwtParseErrorException();
		}
	}

	private void init() {
		Key key;
		try {
			key = getKey(jwtProperties.getSecret().getBytes());
			encryptCipher = Cipher.getInstance("DES");
			encryptCipher.init(Cipher.ENCRYPT_MODE, key);
			decryptCipher = Cipher.getInstance("DES");
			decryptCipher.init(Cipher.DECRYPT_MODE, key);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @return 加密算法
	 */
	private Algorithm getAlgorithm() {
		if (encryptCipher == null) {
			init();
		}
		return Algorithm.HMAC256(jwtProperties.getKey());
	}

	private String encrypt(String strIn) throws Exception {
		return byteArr2HexStr(encrypt(strIn.getBytes()));
	}

	private byte[] encrypt(byte[] arrB) throws Exception {
		return encryptCipher.doFinal(arrB);
	}

	private String decrypt(String strIn) throws Exception {
		return new String(decrypt(hexStr2ByteArr(strIn)));
	}

	private byte[] decrypt(byte[] arrB) throws Exception {
		return decryptCipher.doFinal(arrB);
	}

	private String byteArr2HexStr(byte[] arrB) throws Exception {
		int iLen = arrB.length;
		// 每个byte用两个字符才能表示，所以字符串的长度是数组长度的两倍
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = arrB[i];
			// 把负数转换为正数
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			// 小于0F的数需要在前面补0
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16));
		}
		return sb.toString();
	}

	private byte[] hexStr2ByteArr(String strIn) throws Exception {
		byte[] arrB = strIn.getBytes();
		int iLen = arrB.length;
		// 两个字符表示一个字节，所以字节数组长度是字符串长度除以2
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}

	private Key getKey(byte[] arrBTmp) throws Exception {
		// 创建一个空的8位字节数组（默认值为0）
		byte[] arrB = new byte[8];
		// 将原始字节数组转换为8位
		for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
			arrB[i] = arrBTmp[i];
		}
		// 生成密钥
		Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
		return key;
	}

}
